#include"TcpServer.hpp"
#include"Protocol.hpp"
#include<memory>

Response calculate(const Request& req)
{
    Response res;
    switch(req._op)
    {
        case '+':
            res._result = req._x + req._y;
            break;
        case '-':
            res._result = req._x - req._y;
            break;
        case '*':
            res._result = req._x * req._y;
            break;
        case '/':
            if(req._y == 0) res._code = 1;
            else res._result = req._x / req._y;
            break;
        case '%':
            if(req._y == 0) res._code = 2;
            else res._result = req._x % req._y;
            break;
        default:
            res._code = 3;
            break;       
    }
    return res;
}
void NetCal(Connection* conn, std::string& request)
{
    // 1. 反序列化
    Request req;
    if(!req.Deserialize(request)) return;
    // 2. 业务处理
    Response resp = calculate(req);
    // 3. 序列化,构建应答
    std::string sendStr = resp.Serialize(); 
    Encode(sendStr);
    // 4. 交给服务器conn
    conn->_outbuffer += sendStr;
    // 5. 想办法，让底层的TcpServer，让它开始发送
    // a. 需要有完整的发送逻辑
    // b. 我们触发发送的动作，一旦我们开启EPOLLOUT，epoll会自动立马触发一次发送事件就绪，如果后续保持发送的开启，epoll会一直发送
    conn->_tsvr->EnableReadWrite(conn, true, true);
}
int main()
{
    std::unique_ptr<TcpServer> svr(new TcpServer);
    svr->Dispatcher(NetCal);
    return 0;
}